<template>
  <div class="roles-page">
    <!-- 操作行 -->
    <div class="deal-box">
      <div class="search-box" v-show="showSearch">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px" @submit.native.prevent>
          <el-form-item label="角色名称">
            <el-input
              class="search-input"
              placeholder="请输入查询内容！"
              v-model.trim="queryParams.roleName"
              clearable
              style="width: 240px"
              size="small"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model.trim="queryParams.status" placeholder="请选择" size="small" style="width: 240px">
              <el-option
                v-for="item in typeOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5" v-for="(val,i) of permiList" :key="i">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleDeal(val)"
          v-if="val.funcCode == 'Add'"
        >{{ val.funcName }}</el-button>
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleDeal(val)"
          v-if="val.funcCode == 'Edit'"
        >{{ val.funcName }}</el-button>
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDeal(val)"
          v-if="val.funcCode == 'Delete'"
        >{{ val.funcName }}</el-button>
        <el-button
          type="info"
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-if="val.funcCode == 'ImportExcel'"
        >{{ val.funcName }}</el-button>
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-if="val.funcCode == 'ExprotExcel'"
        >{{ val.funcName }}</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      ref="table"
      style="width: 100%;margin-top:20px;"
      highlight-current-row
      @row-click="rowClickFn"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column type="index" label="序号" width="55" :resizable="false" align="center" fixed></el-table-column>
      <el-table-column prop="roleName" label="角色名称" :resizable="false" align="center"></el-table-column>
      <el-table-column prop="roleDesc" label="角色描述" :resizable="false" align="center"></el-table-column>
      <el-table-column label="角色属性" :resizable="false" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.type == "0" ? '系统管理属性' : '业务操作属性'}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="addTime" label="创建时间" :resizable="false"></el-table-column>
      <el-table-column label="状态" :resizable="false" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model.trim="scope.row.status"
            active-value="1"
            inactive-value="0"
            @change="changeSwitch(scope.row)"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="成员维护" :resizable="false" align="center" >
        <template slot-scope="scope">
          <i class="el-icon-user-solid icon" @click="memberDefendClick(scope.row.roleCode)"></i>
        </template>
      </el-table-column>
      <el-table-column label="权限维护" :resizable="false" align="center" >
        <template slot-scope="scope">
          <i class="el-icon-s-operation icon" @click="authDefendClick(scope.row.roleCode,scope.row.type,scope.row.roleName)"></i>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="pageIndex"
      :limit.sync="pageSize"
      @pagination="getList"
    />
    <!-- 新增编辑弹窗 -->
    <el-dialog :title="title" :visible.sync="show" :close-on-click-modal="false">
      <el-form ref="form" :rules="rules" :model="form" label-width="80px" :disabled="type == 'View'">
        <el-form-item 
          label="角色名称"
          prop="roleName"
          >
          <el-input
            v-model.trim="form.roleName"
            placeholder="请输入角色名称"
          ></el-input>
        </el-form-item>
        <el-form-item 
          label="角色编码"
          prop="roleCode"
          v-if="type != 'Edit'"
          >
          <el-input
            v-model.trim="form.roleCode"
            placeholder="请输入角色编码"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input
            type="textarea"
            v-model.trim="form.roleDesc"
            maxlength="100"
            placeholder="请输入角色描述"
          ></el-input>
        </el-form-item>
        <!-- <el-form-item 
          label="角色状态"
          prop="status"
        >
          <el-select v-model.trim="form.status" placeholder="请选择角色状态">
            <el-option label="启用" value="1"></el-option>
            <el-option label="禁用" value="0"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item 
          label="角色属性"
          prop="type"
        >
          <el-radio-group v-model.trim="form.type">
            <el-radio :disabled="type == 'Edit'" label="0">系统管理类</el-radio>
            <el-radio :disabled="type == 'Edit'" label="1">业务操作类</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item size="large" v-show="type != 'View'">
          <el-button class="cancel-btn" @click="cancel">取消</el-button>
          <el-button type="primary" @click="saveForm">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { listRole, addRole, updateRole, delRole } from "@/api/system/role";
import { pagePermission } from '@/utils/common.js'
export default {
  data() {
    return {
      // 遮罩层
      loading: true,
      tableData: [],
      total: 0, // 总条数
      pageIndex: 1,
      pageSize: 50,
      select_row: null, // 选中当前行
      // 显示搜索条件
      showSearch: true,
      queryParams: {
        roleName: "",
        status: null,
      },
      typeOptions:[
        {
          id:'0',
          name:'禁用'
        },
        {
          id:'1',
          name:'启用'
        }
      ],
      form: { // form数据
        roleCode: "",
        roleName: "",
        roleDesc: "",
        type: "1",
        status: "0"
      },
      title: "",//弹窗表头
      show: false,  // 显示隐藏
      rules: {  // 验证规则
        roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
        roleCode: [{ required: true, message: '请输入角色编码', trigger: 'blur' }],
        status: [{ required: true, message: '请选择角色状态', trigger: 'change' }],
        type: [{ required: true, message: '请输入角色属性', trigger: 'change' }]
      },
      type: '',//当前弹窗状态（新增or编辑）
      ids: [],//选择数组
      // 权限列表
      permiList: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
    };
  },
  components: {},
  mounted(){
    this.getPermissionList()
  },
  created() {
    /**
     * 获取列表
     */
    this.getList()
  },
  watch: {
    select_data(data) {
      this.select_row = [];
      if (data.length > 0) {
        data.forEach(item => {
          this.select_row.push(this.tableData.indexOf(item));
        });
      }
    }
  },
  methods: {
    /**
     * 获取权限列表
     */
    getPermissionList(){
      let name = this.$route.name;
      let allMenu = JSON.parse(localStorage.getItem('allMenu')) 
      pagePermission(name,allMenu,this);
      
    },
    /**
     * 获取列表
     */
    getList() {
      this.loading = true;
      let param = {
        parameter: this.queryParams,
        pageIndex: this.pageIndex,
        pageSize: this.pageSize
      }
      listRole(param).then(res => {
        if(res.status == 200){
          this.tableData = res.data.list;
          this.total = res.data.total;
        }else if(res.status == 102){
          this.tableData = [];
          this.total = 0;
        }
        this.loading = false;
      });
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        roleName: "",
        status: null,
      };
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleDeal(val){
      if(val.funcCode == 'View'){
        this.reset();
        this.type = 'View';
        this.form = {...this.select_row[0]};
        this.show = true;
      }else if(val.funcCode == 'Add'){
        this.type = 'Add';
        this.editRoleFn('Add');
      }else if(val.funcCode == 'Edit'){
        this.type = 'Edit';
        this.editRoleFn('Edit');
      }else if(val.funcCode == 'Delete'){
        this.type = 'Delete';
        this.delClick();
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.pageIndex = 1;
      this.getList();
    },
    changeSwitch(val) {
      let text = val.status === "1" ? "启用" : "禁用";
      this.$confirm('确认要"' + text + '""' + val.roleName + '"角色吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(()=>{
        let sysRole ={
          status: val.status,
          roleCode: val.roleCode
        }
        var data = {
          parameter:{
            sysRole:sysRole
          }
        }
        updateRole(data).then(res => {
            if(res.status == 200){
              this.msgSuccess("修改成功");
              this.getList();
            }else if(res.status == 101){
              this.msgError(res.errors[0].message);
              val.status = val.status === "0" ? "1" : "0";
            }
          }
        );
      }).catch(function() {
        val.status = val.status === "0" ? "1" : "0";
      });
    },
    /**
     * 成员维护
     */
    memberDefendClick(code) {
      this.$router.push({path:"/system/role/member",query:{roleCode:code,childCode:this.$route.name}});
    },
    /**
     * 权限维护
     */
    authDefendClick(code,type,name) {
      this.$router.push({path:"/system/role/auth",query:{roleCode:code,roleType:type,childCode:this.$route.name,roleName: name}});
    },
    /**
     * 表格行选中事件
     */
    rowClickFn(row) {
      // this.select_row = row;
    },
    /**
     * 角色编辑弹窗的显示隐藏
     */
    editRoleFn(type) {
      this.reset();
      this.type = type;
      this.title = type == "Add" ? "新增角色" : "编辑角色";
      if( this.type == "Edit" ){
        if( !this.select_row ){
          this.$message({
            message: '请选择角色栏',
            type: 'warning',
            offset: 60
          });
          return;
        }
        this.form = {...this.select_row[0]};
        delete this.form.addBy
        delete this.form.addTime
        delete this.form.editBy
        delete this.form.editTime
      }
      this.show = true;
    },
    // 表单重置
    reset() {
      this.form = { // form数据
        roleCode: "",
        roleName: "",
        roleDesc: "",
        type: "1",
        status: "1"
      };
      this.resetForm("form");
    },
    /**
     * 角色编辑弹窗提交
     */
    saveForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.type == 'Add') {
            var data = {
              parameter:{
                sysRole:this.form
              }
            }
            addRole(data).then(res => {
                if(res.status == 200){
                  this.msgSuccess("新增成功");
                  this.getList();
                  this.show = false;
                }else if(res.status == 101){
                  this.msgError(res.errors[0].message);
                }
              }
            );
          } else if (this.type == 'Edit'){
            let data = {
              parameter:{
                sysRole:this.form
              }
            }
            updateRole(data).then(res => {
                if(res.status == 200){
                  this.msgSuccess("修改成功");
                  this.getList();
                  this.show = false;
                }else if(res.status == 101){
                  this.msgError(res.errors[0].message);
                }
              }
            );
          } else if (this.type == 'View'){
            this.show = false;
          }
        }
      })
      
    },
    /**
     * 角色编辑弹窗取消
     */
    cancel() {
      console.log(this.form)
      this.show = false;
      this.reset();
    },
    /**
     * 多选框选中数据
     */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.roleCode);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
      this.select_row = selection;
    },
    /**
     * 删除操作
     */
    delClick(){
      let userIds = this.ids;
      if( userIds.length !=0 ){
        userIds = userIds.join(',');
      }else {
        this.msgError("请选择要删除的角色");
        return
      }
      this.$confirm('确定删除角色 '+this.select_row[0].roleName+' ，删除后不可恢复?', '角色删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        let param = {
          parameter: {
            roleCode: userIds
          }
        }
        return delRole(param);
      }).then((res) => {
        if(res.status == 200){
          this.getList();
          this.msgSuccess("删除成功");
        }else if(res.status == 101){
          this.msgError(res.errors[0].message);
        }
      }).catch(()=>{
        
      })
    }
  }
};
</script>

<style lang="scss" scoped>
.roles-page {
  padding: 20px;
  height: 100%;
  box-sizing: border-box  ;
  .deal-box {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .search-box {
      display: flex;
      align-items: center;
      .search-input {
        width: 260px;
        margin-right: 15px;
      }
    }
    .deal-list {
      display: flex;
      align-items: center;
      margin-right: 20px;
      margin-bottom: 20px;
    }
  }
  .icon{
    cursor: pointer;
  }
}
</style>
